//
//  HQUserIdentifier.m
//  edu24app
//
//  Created by ouyongyong on 15/12/28.
//  Copyright © 2015年 edu24ol. All rights reserved.
//

#import "HQUserIdentifier.h"
#import "JSONKit.h"
//#import <AFNetworking/AFNetworkReachabilityManager.h>
#import <AFNetworking/AFHTTPSessionManager.h>
BOOL  enabelTempAppleAuditRole = NO;
static BOOL isNormalUser = NO;
static NSString * const UserIdentifyKey = @"UserIdentifyKey";

static NSString * const testCliCheckApi = @"http://117.121.48.162/interface/v1.0/system/clicheck.php";
static NSString * const cliCheckApi = @"http://app-io.98809.com/interface/v1.0/system/clicheck.php";

#define CheckApi (IsTestEnvironment?testCliCheckApi:cliCheckApi)

@implementation HQUserIdentifier

+ (BOOL)isNormalUser
{
//#ifdef DEBUG
//    isNormalUser = NO;
//    return NO;
//#endif
    
    if (enabelTempAppleAuditRole) {
        return NO;
    }
    
    if (isNormalUser) {
        return YES;
    }
    
#ifdef DEBUG
    isNormalUser = YES;
    return YES;
#endif
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *bundleId = [bundle objectForInfoDictionaryKey:@"CFBundleIdentifier"];
    BOOL isTestEnv = ([bundleId rangeOfString:@"enterprise"].location != NSNotFound);
    
    if (isTestEnv) {
        isNormalUser = YES;
        return YES;
    }
    isNormalUser = ([[self class] userType] == HqUserTypeNormal);
    return isNormalUser;
}

+ (HqUserType)userType
{
    NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    NSNumber *res = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@_%@", UserIdentifyKey, version]];
    if (res) {
        if (res.boolValue == YES) {
            //普通用户
            return HqUserTypeNormal;
        } else {
            //审核人员
            return HqUserTypeReviewer;
        }
    }
    
    //未知
    return HqUserTypeUnknown;
}

+ (NSString *)unitsSuffixText
{
    if ([[self class] isNormalUser]) {
        return @"元";
    } else {
        return @"学点";
    }
}

+ (NSString *)unitsPrefixText
{
    if ([[self class] isNormalUser]) {
        return @"￥";
    } else {
        return @"学点";
    }
}

//+ (void)updateUserIdenfityInfoResult:(void(^)(HqUserType type,BOOL isNormal))resultBlock
//{
//    [UserIdentifier updateUserIdenfityInfoWithVersionId:kAppVersionId appid:kAppId deviceId:[GVUserDefaults standardUserDefaults].hq_deviceId account:[GVUserDefaults standardUserDefaults].hq_userName uid:[NSString stringWithFormat:@"%ld", (long)[GVUserDefaults standardUserDefaults].hq_userId] result:^(HqUserType type) {
//        BOOL isNormal = [self isNormalUser];
//        if (type == HqUserTypeNormal) {
//            isNormal = YES;
//        }
//        if (resultBlock) {
//            resultBlock(type,isNormal);
//        }
//    }];
//}

+ (void)updateUserIdenfityInfoWithVersionId:(NSInteger)versionId
                                      appid:(NSString *)appid
                                   deviceId:(NSString *)deviceId
                                    account:(NSString *)account
                                        uid:(NSString *)uid
{
    [[self class] updateUserIdenfityInfoWithVersionId:versionId appid:appid deviceId:deviceId account:account uid:uid result:nil];
}

+ (void)updateUserIdenfityInfoWithVersionId:(NSInteger)versionId
                                      appid:(NSString *)appid
                                   deviceId:(NSString *)deviceId
                                    account:(NSString *)account
                                        uid:(NSString *)uid
                                     result:(void(^)(HqUserType type))resultBlock
{
    if ([[self class] isNormalUser]) {
        NSLog(@"<UserIdentifier> is normal user");
        if (resultBlock) {
            resultBlock(HqUserTypeNormal);
        }
        return;
    }
    
    NSError* err;
    NSMutableDictionary *dict = @{@"platform" : @(2)}.mutableCopy; //来源，1为android，2为ios，5为macAppstore，6为macOfficial
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *appVersion = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    NSString *buildString = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"];
    NSString *bundleId = [bundle objectForInfoDictionaryKey:@"CFBundleIdentifier"];
    BOOL isTestEnv = ([bundleId rangeOfString:@"enterprise"].location != NSNotFound);
    NSLog(@"Using %@ environment for user identify", isTestEnv?@"test":@"formal");
    
    if (appVersion) {
         [dict setObject:appVersion forKey:@"version"];
    }
    if (appid) {
         [dict setObject:appid forKey:@"appId"];
    }
    if (deviceId) {
         [dict setObject:deviceId forKey:@"deviceId"];
    }
    if (account) {
         [dict setObject:account forKey:@"account"];
    }
    if (uid) {
         [dict setObject:uid forKey:@"uid"];
    }
    if (buildString) {
         [dict setObject:buildString forKey:@"versionId"];
    }
    
    
    
    NSString *url = cliCheckApi;
    
//#ifdef DEBUG
//    if (resultBlock) {
//        resultBlock(HqUserTypeNormal);
//    }
//    return;
//#endif
    
    if (isTestEnv) {
        if (resultBlock) {
            resultBlock(HqUserTypeNormal);
        }
        return;
    }
    
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:dict error:&err];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            NSLog(@"--error reque1:%@",error);
        }
        
        NSError *errorData = nil;
        NSDictionary *dict = @{};
        if (responseObject) {
            dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&errorData];
        }
        
        NSString *responseStr = @"";
        
        if (![dict isKindOfClass:[NSDictionary class]]) {
            dict = @{};
        }
        if (errorData) {
            NSLog(@"解析失败%@",errorData);
        }
        NSNumber *resultCode = dict[@"status"][@"code"];
        NSString* httpCode;
        NSHTTPURLResponse * responseHttp = (NSHTTPURLResponse *)response;
        if (self) {
            httpCode = [NSString stringWithFormat:@"%ld", responseHttp.statusCode];
        } else {
            [self reportFail:@"请求被释放" code:@"-1" msg:@"" rawResp:@""];
        }
        
        if (resultCode && resultCode.intValue == 0) {
            NSNumber *userIdentifyRes = dict[@"data"][@"result"];
            if (userIdentifyRes) {
                NSString *message = [NSString stringWithFormat:@"<UserIdentifier> user is %@ normal user", userIdentifyRes.intValue?@"not":@""];
                NSLog(message);
                NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
                [[NSUserDefaults standardUserDefaults] setObject:@(userIdentifyRes.intValue == 0)  forKey:[NSString stringWithFormat:@"%@_%@", UserIdentifyKey, version]];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                if (userIdentifyRes.intValue) {
                    [self reportFail:@"BadGuy" code:@"0" msg:@"" rawResp:@""];
                    if (resultBlock) {
                        resultBlock(HqUserTypeReviewer);
                    }
                } else {
                    isNormalUser = YES;
                    [self reportSucc:@"User"];
                    if (resultBlock) {
                        resultBlock(HqUserTypeNormal);
                    }
                }
            } else {
                NSLog(@"<UserIdentifier> idenfity fail for invalid resultCode %@", resultCode);
                [self reportFail:@"data格式错误" code:httpCode msg:responseStr rawResp:responseStr];
                if (resultBlock) {
                    resultBlock(HqUserTypeUnknown);
                }
            }
        } else {
            NSLog(@"<UserIdentifier> idenfity fail with response %@", responseStr);
            [self reportFail:@"返回格式错误" code:httpCode msg:responseStr rawResp:responseStr];
            if (resultBlock) {
                resultBlock(HqUserTypeUnknown);
            }
        }
        
    }]resume];
}

+ (void)reportFail:(NSString *)failType code:(NSString *)failCode msg:(NSString *)failMsg rawResp:(NSString *)rawResp
{
//    [[HiidoSDK sharedObject] reportFailure:[GVUserDefaults standardUserDefaults].hq_userId actionId:@"USER_TYPE" actionType:failType failCode:failCode failMessage:failMsg parm:rawResp];
}

+ (void)reportSucc:(NSString *)userType
{
//    [[HiidoSDK sharedObject] reportSuccess:[GVUserDefaults standardUserDefaults].hq_userId actionId:@"USER_TYPE" actionType:userType duration:0 parm:nil];
}
@end



